<template>
  <div class="app-container"> 
    <el-form :inline="true" :model="listQuery" class="demo-form-inline">
       <i class="el-icon-search btn-search" @click="handleShowSearch()"></i>
      <div class="btn-box">  <el-button   type="primary"  @click="handleaddUser()">添加用户</el-button></div>
      <div   v-show="showbtns==true"  class="search-lf">
          <el-form-item label="用户名">
        <el-input v-model="listQuery.name" placeholder="用户名"></el-input>
      </el-form-item>
      <el-form-item label="账号">
        <el-input v-model="listQuery.memberName" placeholder="账号"></el-input>
      </el-form-item>
     
      <el-form-item label="是否禁用">
        <el-select filterable v-model="listQuery.state" placeholder="是否禁用">
          <el-option label="是" value="0"></el-option>
          <el-option label="否" value="1"></el-option>
        </el-select>
      </el-form-item>
       <el-form-item>
        <el-button  type="primary" plain  @click="getList()">查询</el-button>
      
      </el-form-item>
      </div>
      
     

     
    </el-form>
    <el-table
       v-loading="listLoading"  border
 height='650px'
      :data="list"
          fit
       highlight-current-row
      style="width: 100%"
    >
      <el-table-column align="center" width='60px' label="序号">
        <template slot-scope="scope">
          <span>{{scope.$index+1 }}</span>
        </template>
      </el-table-column>
     

      <el-table-column align="center" label="用户名">
        <template slot-scope="{row}">
          <span>{{ row.memberName }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="手机号">
        <template slot-scope="{row}">
          <span>{{ row.mobile }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="邮箱">
        <template slot-scope="{row}">
          <span>{{ row.email }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="是否禁用">
        <template slot-scope="{row}">
          <el-switch
           active-color="#d9d9d9"
           inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="0"
            @change="handleState(row)"
            v-model="row.state"
          ></el-switch>
        </template>
      </el-table-column>
   
       <el-table-column align="center" label="战区">
        <template slot-scope="{row}">
          <el-tag>{{ row.regionName}}</el-tag>
        </template>
      </el-table-column>
       <el-table-column align="center"  label="省份">
        <template slot-scope="{row}">
          <el-tag>{{ row.provinceName }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="220">
        <template slot-scope="{row}">
          <el-button
            type="primary"
            @click="handleEdit(row)"
            size="mini"
           :disabled='editDisabled==true'   icon="el-icon-edit"
          >编辑</el-button>

          <el-button
            class="mg-l"
            @click="handlePerssion(row)"
            type="warning"
            size="mini"
            icon="el-icon-setting"
          >分配</el-button>
          <el-button
            @click="handleDel(row.id)"
            class="mg-l"
            type="danger"
            size="mini"
            icon="el-icon-delete"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog @close='handleClose' :visible.sync="dialogVisible" :title="dialogType==='edit'?'编辑用户':'添加用户'">
      <el-form label-width="80px" ref="usersList" :model="usersList" label-position="left">
        <el-form-item label="用户账号">
          <el-input v-model="usersList.memberName" placeholder="请输入用户账号" />
        </el-form-item>

        <el-form-item label="真实姓名">
          <el-input v-model="usersList.name" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="usersList.password" placeholder="请输入密码" />
        </el-form-item>
       
        <el-form-item label="手机号">
          <el-input v-model="usersList.mobile" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="usersList.email" placeholder="请输入邮箱" />
        </el-form-item>
            <el-form-item label="战区">
          <el-select filterable
            v-model="usersList.regionName"
            @change="handleChangeRegio($event)"
            placeholder="请选择"
          >
            <el-option
              v-for="item in RegionList"
              :key="item.regionId"
              :label="item.region"
              :value="item.region"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="省份">
          <el-select filterable
            v-model="usersList.provinceName"
            @change="handleChangePro($event)"
            placeholder="请选择"
          >
            <el-option
              v-for="item in rgionProList"
              :key="item.provinceId"
              :label="item.provinceName"
              :value="item.provinceName"
            ></el-option>
          </el-select>
        </el-form-item>
    
      </el-form>
      <div style="text-align:right;">
         <el-button type="primary" @click="confirmRole">确定</el-button>
       <el-button type="danger" class="cancel_border" plain  @click="dialogVisible=false;editDisabled=false">取消</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisibleMenu" title="角色分配">
      <el-form label-width="80px" label-position="left">
        <el-form-item label>
          <el-tree
            ref="tree"
            :check-strictly="checkStrictly"
            :data="rolesData"
            :props="defaultProps"
            show-checkbox
            node-key="id"
            :default-expanded-keys="defaultExpandKey"
               :default-checked-keys="defaultExpandKey"
            @check-change="handleCheckChange"
            class="permission-tree"
          />
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisibleMenu=false">取消</el-button>
        <el-button type="primary" @click="confirmRolePerm()">确定</el-button>
      </div>
    </el-dialog>
    <pagination
      v-show="total>=20"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import {
  userList,
  addUser,
  updateUser,
  updateUserState,
  updateUserPermission,
  deleteUser,
  regiosList,
  getUserById
} from "@/api/user";
import { roleList } from "@/api/role";
import { RegionsProvince } from "@/api/region";
import { Message } from "element-ui";
import Pagination from "@/components/Pagination"; // Secondary package based on el-pagination
const defaultRole = {
  key: "",
  name: "",

  roles: [],
};
export default {
  name: "userList",

  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        1: "男",
        0: "女",
      };
      return statusMap[status];
    },
  },
  data() {
    return {
      showbtns: false,
     defaultExpandKey:[],
     defaultChecked:[],
      downloadLoading:false,
      RegionList:[],
      list: [], editDisabled:false,
 rgionProList:[],
      downloadLoading:false,
      usersList: {
        memberName: "", //	用户账号

        password: "", //	用户密码

        name: "", //	真实姓名

        mobile: "", //	用户手机号

        email: "", //用户邮箱

        sex: "1", //性别
      },
      total: 0,
      dialogVisibleMenu: false,
      listLoading: true,
      listQuery: {
        access_token: sessionStorage.getItem("token"),
        page: 1,

        name: "",

        state: "",
        pageSize: 20,
      },
      roles: [],
      role: Object.assign({}, defaultRole),
      userId: "", //用户id
      rolesList:[],

      dialogVisible: false,
      dialogType: "new",
      checkStrictly: false,
      defaultProps: {
        children: "childMenu",
        label: "name",
      },
      ids: "",
    };
  },
  created() {
    this.getList();
    this.getroles();
  },
  computed: {
    rolesData() {
      return this.roles;
    },
  },
 methods: {
      handleClose(){
      this.editDisabled = false;
    },
    handleShowSearch() {
      this.showbtns = !this.showbtns;
    },
    handleChangePro(id) {
       
      let obj = {};
      obj = this.rgionProList.find((item) => {
        //model就是上面的数据源
        return item.provinceName === id; //筛选出匹配数据
      });

      this.usersList.provinceId = obj.provinceId;
    },
    handleChangeRegio(id) {
     
      let obj = {};
      obj = this.RegionList.find((item) => {
        //model就是上面的数据源
        return item.region === id; //筛选出匹配数据
      }); 
      
     RegionsProvince(obj.id).then((res) => {
      
        this.rgionProList = res.data.data;
       
      });
      this.usersList.regionId = obj.id;
    },
    handleState(row) {
      // let data = {
      //   state:
      // };
      updateUserState(row.id, row.state).then((res) => {
        if (res.data.code == "200") {
          this.$message.success(res.data.message);
          this.getList();
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
       getList() {
       this.editDisabled = false;
     
      regiosList().then((res) => {
        this.RegionList = res.data.data;
      });

      this.listLoading = true;
      userList(this.listQuery)
        .then((response) => {
          this.list = response.data.data.rows;
          this.total = response.data.data.total;
          this.listLoading = false;
        })
        .catch(() => {
          this.listLoading = false;
        });
    },
    handleDel(id) {
      this.$confirm("确定删除该用户么?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "error",
      })
        .then(() => {
          deleteUser(id).then((res) => {
            if (res.data.code == "200") {
              this.$message.success(res.data.message);
              this.getList();
            } else {
              this.$message.error(res.data.message);
            }
          });
         
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    getroles() {
      roleList(sessionStorage.getItem("token")).then((res) => {
        this.roles = res.data.data.rows;
       
      });
    },
    handleCheckChange(data, checked, indeterminate) {
      console.log(data, checked, indeterminate);
    },
    handlePerssion(row) {
      this.dialogVisibleMenu = true;
    
      this.userId = row.id;
      getUserById(this.userId).then((res)=>{
        let resd=[];
       //  resd.push(res.data.data.roles[0].id);
         res.data.data.roles.forEach(item=>{
           resd.push(item.id)
         })
          this.defaultExpandKey=resd;
          this.$refs.tree.getCheckedNodes()
      
         
      })
      // defaultChecked
    },

    confirmRolePerm() {
      this.checkStrictly = true;

      let checkedList = this.$refs.tree.getCheckedKeys();
      let res = [];
      if (checkedList.length > 0) {
        checkedList.forEach((r) => {
          res.push(r);
        });
        this.ids = res.join(",");
      }

       
      let data = {
        roleIds: this.ids,
      };
      updateUserPermission(this.userId, data).then((res) => {
        if (res.data.code == "200") {
          this.$message.success(res.data.message);
          this.dialogVisibleMenu = false;
          this.getList();
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    handleaddUser() {
    
       this.usersList={}
      this.dialogType = "new";
      this.dialogVisible = true;
       this.$nextTick(() => {
        this.$refs['usersList'].clearValidate()
      })
    },
      handleEdit(row) {
       this.editDisabled=true;
      this.dialogType = "edit"
      this.dialogVisible = true;
      
      this.usersList = row;
      this.usersList.password=''
      this.userId = row.id;
    },
    confirmRole(id) {
     const isEdit = this.dialogType ==="edit";
      if (isEdit) {
       
        updateUser( this.usersList).then((res) => {
          if (res.data.code == "200") {
            this.$message.success(res.data.message);
            this.dialogVisible = false;
            this.getList();
             this.editDisabled=false;
          } else {
            this.$message.error(res.data.message);
          }
        });
        return false;
      }
      let _this = this;
      let data = {};

      addUser(this.usersList).then((res) => {
       
        if (res.data.code == 200) {
           
          this.$message.success(res.data.message);
         
          _this.dialogVisible = false;
          _this.userList = "";
          _this.getList();
        }else{
           this.$message.error(res.data.message);
         
        }
      });
    },
  },

};
</script>

<style scoped>
.edit-input {
  padding-right: 100px;
}
.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}
</style>
